import axios from '@/utils/request'

export default {
  Promotion: {
    form: {
      fields: [
        'name',
        { property: 'template', tab: '高级', relation_filter: { '@filter': 'entity.getEnabled()' }},
        { property: 'enabled', default_value: true, required: false },
        {
          property: 'specifications', required: false,
          // NOTICE: Use transfer type, default value must be set to []
          type: 'transfer', default_value: [],
          help: '可选，特定规格活动，留空为所有参加规格参加活动'
        },
        'startTime',
        'endTime',
        {
          property: 'config',
          tab: '高级',
          component: {
            components: { FormAdmin: () => import('@/components/EasyAdmin/FormAdmin') },
            data() {
              return {
                promotionTemplate: {},
                refreshKey: 0
              }
            },
            methods: {
              reloadTemplateConfig(templateId) {
                if (templateId) {
                  axios.get(`/manage/promotion-templates/${templateId}`)
                    .then(res => {
                      this.promotionTemplate = res.data

                      // TODO: with some bugs in 'default_value'
                      this.refreshKey++
                    })
                }
              }
            },
            props: ['form', 'property'],
            watch: {
              'form.template': {
                handler(value, oldValue) {
                  this.reloadTemplateConfig(value)
                },
                immediate: true
              }
            },
            created() {
              if (this.form['template']?.id) {
                this.reloadTemplateConfig(this.form['template'].id)
              }
            },
            render(h) {
              return (
                <form-admin
                  key={this.refreshKey}
                  v-model={this.form[this.property]}
                  entity-conf='Promotion'
                  fields={this.promotionTemplate?.fields}
                >
                  <template slot='title'>
                    <span />
                  </template>

                  <template slot='action'>
                    <span />
                  </template>
                </form-admin>
              )
            }
          }
        },
        'description'
      ]
    },
    list: {
      query: {
        '@order': 'entity.createdTime|DESC'
      },
      list_filter: {
        'template.id': () => {
          return axios
            .get('/manage/promotion-templates')
            .then(res =>
              Object.assign({ __label: '模板' },
                ...res.data.map(v => { return { [v.id]: v.name } })))
        }
      },
      list_display: [
        'id',
        'name',
        'template',
        { property: 'enabled', editable: true },
        'specifications',
        'startTime',
        'endTime'
      ]
    }
  }
}
